/*
 * @Author: mayijun
 * @Date: 2022-05-05 09:59:32
 * @LastEditors: mayijun
 * @LastEditTime: 2022-08-10 11:01:52
 */
import cookie from 'js-cookie';
import dayjs from 'dayjs'
// 普通函数
const isIpPort = (str: string) => {
  const arr1 = str.split(':') as any;
  if (arr1.length === 2) {
    const ip = arr1[0];
    const arr = ip.split('.');
    if (arr.length === 4) {
      return {
        is: true,
        ip: ip
      };
    }
  }
  return {
    is: false,
    ip: ''
  };
};
/**
 * @description 判断字符串是否为空
 * @param {String} str
 */
const isStrEmpty = (str: string) => {
  return typeof str !== 'string' || !str || str == '';
};
export const getDomain = () => {
  let href = window.location.href;
  try {
    href = href.replace('http://', '').replace('https://', '');
    href = href.split('/')[0];
    console.log(href);
    const res = isIpPort(href);
    if (res.is) {
      return res.ip;
    }
    const splited = href.split('.');
    href = splited.splice(1, splited.length - 1).join('.');
    return href;
  } catch (error) {
    console.error(error);
    return href;
  }
};
export const setCookie = (key: string, token: string) => {
  if (isStrEmpty(token)) {
    console.error('cookie设置token为空！');
    return;
  }
  cookie.set(key, token, {
    domain: getDomain(),
    expires: 30
  });
};
interface MenuItem {
  resourceCode: string;
  resourceLink: string;
  resourceName: string;
  childrens: MenuItem[];
}

const whiteList = process.env.VUE_APP_whiteList?.split(',') ?? [];

export const checkUserMenuPage = (menuList: MenuItem[], toPath: string) => {
  let backStatus = false as boolean;
  // if (toPath === '/404' || toPath === '/home') {
  if (whiteList.find((i: string) => toPath.startsWith(i))) {
    return true;
  }
  menuList.forEach((element: MenuItem) => {
    if (element.resourceLink === toPath) {
      backStatus = true;
    }
    if (element.childrens && element.childrens && !backStatus) {
      backStatus = checkUserMenuPage(element.childrens, toPath);
    }
  });
  return backStatus;
};
export const getCookie = (key: string) => {
  const t = cookie.get(key) as string;
  return t;
};
export const clearCookie = (key: string) => {
  cookie.remove(key, {
    path: '/',
    domain: getDomain(),
    expires: -1
  });
};
export const backPreviousSys = (str: string) => {
  let url: any = process.env.VUE_APP_LOGINURL;
  window.location.href = url;
};
/**
 * @description 删除对象空属性
 * @param {Object} obj
 */
export function delEmptyVal(obj: any) {
  for (const key in obj) {
    if (obj[key] === '' || obj[key] === undefined) {
      delete obj[key];
    }
  }
  return obj;
}

/**
 * @description 后端映射数据转换成对象数组
 * @param {Object} obj
 */
interface IKey {
  [propName: string]: any;
}
export function handleSceneMap(obj: any) {
  const resArr = [];
  for (const key in obj) {
    const objChild: IKey = {};
    objChild.key = key;
    objChild.value = obj[key];
    resArr.push(objChild);
  }
  return resArr;
}

interface objectNotEmpty {
  [propName: string]: any;
}

export const rebuildObject = (params: objectNotEmpty) => {
  if (!params) return;
  const keys: string[] = Object.keys(params);
  const newObj: objectNotEmpty = {};
  keys.forEach((item) => {
    if (params[item]) {
      newObj[item] = params[item];
    }
  });
  return newObj;
};

/* 匹配key值 赋值 */
export const setFieldsValue = (nv: any, ov: any) => {
  if (!Object.keys(nv).length || !Object.keys(ov).length) return;
  Object.keys(nv).forEach((key: any) => {
    nv[key] = ov[key] || nv[key];
  });
};

type TargetContext = '_self' | '_parent' | '_blank' | '_top';

export const openWindow = (
  url: string,
  opts?: { target?: TargetContext;[key: string]: any }
) => {
  const { target = '_blank', ...others } = opts || {};
  window.open(
    url,
    target,
    Object.entries(others)
      .reduce((preValue: string[], curValue) => {
        const [key, value] = curValue;
        return [...preValue, `${key}=${value}`];
      }, [])
      .join(',')
  );
};

/** 千分位 */
export function numberToCurrencyNo(value: number) {
  if (!value) return 0
  // 获取整数部分
  const intPart = Math.trunc(value)
  // 整数部分处理，增加,
  const intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
  // 预定义小数部分
  let floatPart = ''
  // 将数值截取为小数部分和整数部分
  const valueArray = value.toString().split('.')
  if (valueArray.length === 2) { // 有小数部分
    floatPart = valueArray[1].toString().slice(0, 2) // 取得小数部分且最多两位小数
    return intPartFormat + '.' + floatPart
  }
  return intPartFormat + floatPart
}

//获取周的日期格式
export const getYearWeek = (date: any) => {
  let y = new Date().getFullYear(); //获取年份
  let startDate = new Date(y, 0, 1);
  let d = Math.round((date.valueOf() - startDate.valueOf()) / 86400000);
  return y + '-' + Math.ceil((d + (startDate.getDay() + 1 - 1)) / 7);
};
//根据周的日期格式获取日期格式
export const getDateOfWeek = (w: any, y: any) => {
  var simple = new Date(y, 0, 1 + (w - 1) * 7);
  var dow = simple.getDay();
  var weekStart = simple;
  if (dow <= 4) {
    weekStart.setDate(simple.getDate() - simple.getDay() + 1);
  } else {
    weekStart.setDate(simple.getDate() + 8 - simple.getDay());
  }
  return dayjs(weekStart).format('YYYY-MM-DD');
};

export const getQuerterFormatter = (value: any) => {
  let quarter: any = ''
  if (value && value.indexOf('01') != -1) {
    quarter = value.substr(0, 5) + 'Q1';
  } else if (value && value.indexOf('04') != -1) {
    quarter = value.substr(0, 5) + 'Q2';
  } else if (value && value.indexOf('07') != -1) {
    quarter = value.substr(0, 5) + 'Q3';
  } else if (value && value.indexOf('10') != -1) {
    quarter = value.substr(0, 5) + 'Q4';
  }
  return quarter
}

export const showQuerterFormatter = (value: any) => {
  let quarter: any = ''
  if (value && value.indexOf('Q1') != -1) {
    quarter = value.substring(0, 5) + '01';
  } else if (value && value.indexOf('Q2') != -1) {
    quarter = value.substring(0, 5) + '04';
  } else if (value && value.indexOf('Q3') != -1) {
    quarter = value.substring(0, 5) + '07';
  } else if (value && value.indexOf('Q4') != -1) {
    quarter = value.substring(0, 5) + '10';
  }
  return quarter
}

export const removeAllChildDom = (child: any) => {
  // var child= document.getElementsByClassName("tempDiv");
  console.log('child', child)
  child.removeNode = [];
  if (child.length != undefined) {
    var len = child.length;
    for (var i = 0; i < len; i++) {
      child.removeNode.push({
        parent: child[i].parentNode,
        inner: child[i].outerHTML,
        next: child[i].nextSibling
      });
    }
    for (var i = 0; i < len; i++) {
      child[0].parentNode.removeChild(child[0]);
    }
  } else {
    child.removeNode.push({
      parent: child.parentNode,
      inner: child.outerHTML,
      next: child.nextSibling
    });
    child.parentNode.removeChild(child);
  }
}

